package metrics

import (
	"sync"
	"time"
)

type TPSAnalyser struct {
	sync.RWMutex
	name          string
	startTime     int64
	intervalCount int64
}

var DTSRegisterTPSAnalyser = NewTPSAnalyser("DTS-Register-TPS-Analyser")
var DTSEnlistTPSAnalyser = NewTPSAnalyser("DTS-Enlist-TPS-Analyser")
var DTSTryResultReportTPSAnalyser = NewTPSAnalyser("DTS-Try-Result-Report-TPS-Analyser")
var DTSCallbackConfirmTPSAnalyser = NewTPSAnalyser("DTS-Callback-Confirm-TPS-Analyser")
var DTSCallbackCancelTPSAnalyser = NewTPSAnalyser("DTS-Callback-Cancel-TPS-Analyser")

func NewTPSAnalyser(name string) *TPSAnalyser {
	tpsAnalyser := &TPSAnalyser{
		name:      name,
		startTime: time.Now().Unix(),
	}

	return tpsAnalyser
}

func (t *TPSAnalyser) IncreaseCount() {
	t.Lock()
	t.intervalCount++
	t.Unlock()
}

func (t *TPSAnalyser) GetTPSOfIntervalCountingTimeAndReset() float64 {
	t.Lock()
	defer func() {
		t.intervalCount = 0
		t.startTime = time.Now().Unix()
		t.Unlock()
	}()
	now := time.Now().Unix()
	interval := now - t.startTime
	if interval > 0 {
		return float64(t.intervalCount) / float64(interval)
	} else {
		return 0.0
	}
}
